<template>
  <div class="sign-in-page">
    <el-tabs v-model="activeTab" class="sign-tabs">
      <el-tab-pane label="待签到活动" name="pending">
        <div class="activities-container">
          <el-empty v-if="!pendingActivities.length" description="暂无待签到活动" />
          <el-card v-else v-for="activity in pendingActivities" :key="activity.activityId" class="activity-card">
            <div class="activity-header">
              <el-tag :type="getTypeTag(activity.type)" size="large">
                {{ getActivityType(activity.type) }}
              </el-tag>
              <span class="time-info">
                {{ formatDateTime(activity.startTime) }} 至 {{ formatDateTime(activity.endTime) }}
              </span>
            </div>
            <div class="activity-footer">
              <span class="remaining-time">{{ activity.timeStatus }}</span>
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  @click="handleNormalSign(activity)"
                  v-if="activity.type === 'normal'"
                >
                  签到
                </el-button>
                <el-button 
                  type="warning" 
                  @click="handleCodeSign(activity)"
                  v-if="activity.type === 'code'"
                >
                  签到码签到
                </el-button>
                <el-button 
                  type="success" 
                  @click="handleQRSign(activity)"
                  v-if="activity.type === 'qr'"
                >
                  扫码签到
                </el-button>
                <el-button 
                  type="info" 
                  @click="handleGestureSign(activity)"
                  v-if="activity.type === 'gesture'"
                >
                  九宫格签到
                </el-button>
                <el-button 
                  type="danger" 
                  @click="handleLocationSign(activity)"
                  v-if="activity.type === 'location'"
                >
                  位置签到
                </el-button>
                
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="签到记录" name="records">
        <div class="records-container">
          <el-empty v-if="!signRecords.length" description="暂无签到记录" />
          <el-table v-else :data="signRecords" style="width: 100%">
            <el-table-column prop="activityType" label="签到类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getTypeTag(row.type)">{{ getActivityType(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="signTime" label="签到时间" width="200">
              <template #default="{ row }">
                {{ formatDateTime(row.signTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 签到码输入对话框 -->
    <el-dialog v-model="codeDialogVisible" title="请输入签到码" width="300px">
      <el-input v-model="signCode" placeholder="请输入签到码" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="codeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCodeSign" :loading="signing">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 扫码签到对话框 -->
    <el-dialog
      v-model="qrDialogVisible"
      title="扫码签到"
      width="90%"
      fullscreen
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="qr-dialog"
    >
      <QRScanner @close="handleScannerClose" v-if="qrDialogVisible" />
    </el-dialog>

    <!-- 九宫格签到对话框 -->
    <el-dialog v-model="gestureDialogVisible" title="九宫格签到" width="300px">
      <el-input v-model="gesturePattern" placeholder="请输入九宫格手势密码（如：1,2,3,4）" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gestureDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGestureSign" :loading="signing">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 位置签到对话框 -->
    <el-dialog v-model="locationDialogVisible" title="位置签到" width="400px">
      <el-form :model="locationForm" label-width="80px">
        <el-form-item label="纬度">
          <el-input v-model="locationForm.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="locationForm.lon" placeholder="请输入经度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="locationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLocationSign" :loading="signing">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import QRScanner from '@/components/QRScanner.vue'
import {
  getPendingSignActivities,
  getSignRecords,
  normalSign,
  codeSign,
  gestureSign,
  locationSign
} from '@/api/student'

const activeTab = ref('pending')
const pendingActivities = ref([])
const signRecords = ref([])
const codeDialogVisible = ref(false)
const qrDialogVisible = ref(false)
const gestureDialogVisible = ref(false)
const locationDialogVisible = ref(false)
const signCode = ref('')
const gesturePattern = ref('')
const locationForm = ref({
  lat: '',
  lon: ''
})
const signing = ref(false)
const currentActivity = ref(null)

// 获取活动类型
const getActivityType = (type) => {
  const types = {
    normal: '普通签到',
    code: '签到码',
    qr: '二维码',
    gesture: '九宫格',
    location: '位置签到'
  }
  return types[type] || type
}

// 获取类型标签样式
const getTypeTag = (type) => {
  const tags = {
    normal: '',
    code: 'warning',
    qr: 'success',
    gesture: 'info', // 新增
    location: 'danger' // 新增
  }
  return tags[type] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString()
  const day = date.getDate().toString()
  const hour = date.getHours().toString().padStart(2, '0')
  const minute = date.getMinutes().toString().padStart(2, '0')
  const second = date.getSeconds().toString().padStart(2, '0')
  return `${year}年${month}月${day}日${hour}时${minute}分${second}秒`
}

// 获取待签到活动
const fetchPendingActivities = async () => {
  try {
    const response = await getPendingSignActivities()
    if (response.code === 200) {
      pendingActivities.value = response.data
    }
  } catch (error) {
    console.error('获取待签到活动失败:', error)
    ElMessage.error('获取待签到活动失败')
  }
}

// 获取签到记录
const fetchSignRecords = async () => {
  try {
    const response = await getSignRecords()
    if (response.code === 200) {
      signRecords.value = response.data
    }
  } catch (error) {
    console.error('获取签到记录失败:', error)
    ElMessage.error('获取签到记录失败')
  }
}

// 普通签到
const handleNormalSign = async (activity) => {
  try {
    signing.value = true
    const response = await normalSign(activity.activityId)
    if (response.code === 200) {
      ElMessage.success('签到成功')
      await fetchPendingActivities()
      await fetchSignRecords()
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    signing.value = false
  }
}

// 打开签到码对话框
const handleCodeSign = (activity) => {
  currentActivity.value = activity
  signCode.value = ''
  codeDialogVisible.value = true
}

// 提交签到码
const submitCodeSign = async () => {
  if (!signCode.value) {
    ElMessage.warning('请输入签到码')
    return
  }

  try {
    signing.value = true
    const response = await codeSign(currentActivity.value.activityId, {
      signCode: signCode.value
    })
    if (response.code === 200) {
      ElMessage.success('签到成功')
      codeDialogVisible.value = false
      await fetchPendingActivities()
      await fetchSignRecords()
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    signing.value = false
  }
}

// 打开扫码签到对话框
const handleQRSign = (activity) => {
  currentActivity.value = activity
  qrDialogVisible.value = true
}

// 处理扫码结果
const handleScannerClose = async (success) => {
  qrDialogVisible.value = false
  if (success) {
    await fetchPendingActivities()
    await fetchSignRecords()
  }
}

// 九宫格签到
const handleGestureSign = (activity) => {
  currentActivity.value = activity
  gesturePattern.value = ''
  gestureDialogVisible.value = true
}

// 提交九宫格签到
const submitGestureSign = async () => {
  if (!gesturePattern.value) {
    ElMessage.warning('请输入九宫格手势密码')
    return
  }

  try {
    signing.value = true
    const response = await gestureSign(currentActivity.value.activityId, {
      gesturePoint: gesturePattern.value
    })
    if (response.code === 200) {
      ElMessage.success('签到成功')
      gestureDialogVisible.value = false
      await fetchPendingActivities()
      await fetchSignRecords()
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    signing.value = false
  }
}

// 位置签到
const handleLocationSign = (activity) => {
  currentActivity.value = activity
  locationForm.value.lat = ''
  locationForm.value.lon = ''
  locationDialogVisible.value = true
}

// 提交位置签到
const submitLocationSign = async () => {
  if (!locationForm.value.lat || !locationForm.value.lon) {
    ElMessage.warning('请输入完整的经纬度信息')
    return
  }

  try {
    signing.value = true
    const response = await locationSign(currentActivity.value.activityId, {
      lat: locationForm.value.lat,
      lon: locationForm.value.lon
    })
    if (response.code === 200) {
      ElMessage.success('签到成功')
      locationDialogVisible.value = false
      await fetchPendingActivities()
      await fetchSignRecords()
    } else {
      ElMessage.error(response.message || '签到失败')
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    signing.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchPendingActivities()
  fetchSignRecords()
})
</script>

<style scoped>
.sign-in-page {
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
}

.sign-tabs {
  height: 100%;
}

.activities-container {
  padding: 20px 0;
}

.activity-card {
  margin-bottom: 20px;
}

.activity-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 15px;
}

.time-info {
  color: #606266;
  font-size: 14px;
}

.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.remaining-time {
  color: #409EFF;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.records-container {
  padding: 20px 0;
}

:deep(.el-dialog.qr-dialog) {
  margin: 0;
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  
  .el-dialog__body {
    height: calc(100% - 54px);
    padding: 0;
  }
}
</style>